package system

import (
	"fmt"
	"math"
	"strings"
	"sort"

	"atools/models"
	"atools/utils"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// SearchKeyWords 处理关键词搜索，支持智能拼音匹配
func (app *App) SearchKeyWords(keywords string) []models.InstalledApp {
	var result []models.InstalledApp
	if len(strings.TrimSpace(keywords)) == 0 {
		return getDefaultApps()
	}

	// 简化调试信息，减少输出
	fmt.Printf("搜索: %s (应用总数: %d)\n", keywords, len(app.InstalledApp))

	// 记录匹配分数，用于排序
	type scoredApp struct {
		app   models.InstalledApp
		score int
	}
	var scoredResults []scoredApp

	// 预分配切片容量，提高性能
	scoredResults = make([]scoredApp, 0, len(app.InstalledApp)/4)

	// 对每个应用进行匹配
	for _, installedApp := range app.InstalledApp {
		// 使用智能拼音匹配
		matched, score := utils.MatchPinyin(installedApp.Name, keywords)
		
		if matched {
			// 收藏应用加分
			if installedApp.IsFavorite {
				score += 10
			}
			
			// 最近使用的应用加分
			if !installedApp.LastUsed.IsZero() {
				score += 5
			}
			
			// 使用频率加分
			if installedApp.UseCount > 0 {
				score += min(installedApp.UseCount, 10) // 最多加10分
			}
			
			scoredResults = append(scoredResults, scoredApp{
				app:   installedApp,
				score: score,
			})
		}
	}

	// 按分数排序
	sort.Slice(scoredResults, func(i, j int) bool {
		if scoredResults[i].score == scoredResults[j].score {
			// 分数相同时，按使用次数排序
			return scoredResults[i].app.UseCount > scoredResults[j].app.UseCount
		}
		return scoredResults[i].score > scoredResults[j].score
	})

	// 转换为结果列表，限制最大结果数量
	maxResults := app.Preferences.MaxResults
	if maxResults <= 0 {
		maxResults = 20 // 默认最多20个结果
	}
	
	// 预分配结果切片
	result = make([]models.InstalledApp, 0, min(len(scoredResults), maxResults))
	
	for i, scored := range scoredResults {
		if i >= maxResults {
			break
		}
		result = append(result, scored.app)
	}

	// 如果没有结果，返回默认应用
	if len(result) == 0 {
		return getDefaultApps()
	}

	// 简化调试输出
	fmt.Printf("匹配结果: %d 个\n", len(result))
	
	app.setWindowHeight(result)
	return result
}

// min 辅助函数
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// GetSearchSuggestions 获取搜索建议
func (app *App) GetSearchSuggestions(keywords string) []string {
	if len(strings.TrimSpace(keywords)) == 0 {
		return []string{}
	}
	
	var suggestions []string
	keywordsLower := strings.ToLower(keywords)
	
	// 收集可能的匹配项
	suggestionMap := make(map[string]bool)
	
	for _, installedApp := range app.InstalledApp {
		appNameLower := strings.ToLower(installedApp.Name)
		
		// 如果应用名包含关键词，添加完整应用名作为建议
		if strings.Contains(appNameLower, keywordsLower) && !suggestionMap[installedApp.Name] {
			suggestions = append(suggestions, installedApp.Name)
			suggestionMap[installedApp.Name] = true
		}
		
		// 如果是拼音匹配，也添加应用名
		if matched, _ := utils.MatchPinyin(installedApp.Name, keywords); matched && !suggestionMap[installedApp.Name] {
			suggestions = append(suggestions, installedApp.Name)
			suggestionMap[installedApp.Name] = true
		}
	}
	
	// 限制建议数量
	if len(suggestions) > 8 {
		suggestions = suggestions[:8]
	}
	
	return suggestions
}

// SearchWithSuggestions 搜索并返回建议
func (app *App) SearchWithSuggestions(keywords string) models.SearchResult {
	apps := app.SearchKeyWords(keywords)
	suggestions := app.GetSearchSuggestions(keywords)
	
	return models.SearchResult{
		Apps:        apps,
		Suggestions: suggestions,
		TotalCount:  len(apps),
	}
}

func (app *App) ClearMatcherResult() {
	println("ClearMatcherResult")
	// 不应该清空 InstalledApp，这会导致后续搜索失败
	// 只需要重置窗口高度即可
	app.setWindowHeight([]models.InstalledApp{})
}

func (app *App) setWindowHeight(result []models.InstalledApp) {
	if len(result) == 0 {
		runtime.WindowSetSize(app.Ctx, app.WindowWidth, app.CellHeight)
		return
	}
	
	// 计算需要显示的行数，每行最多显示8个应用
	itemsPerRow := 8
	lineNum := int(math.Ceil(float64(len(result)) / float64(itemsPerRow)))
	
	// 设置最大高度，避免窗口过大
	maxLines := 5
	if lineNum > maxLines {
		lineNum = maxLines
	}
	
	runtime.WindowSetSize(app.Ctx, app.WindowWidth, lineNum*app.CellHeight+app.CellHeight)
}

func getDefaultApps() []models.InstalledApp {
	return []models.InstalledApp{
		{
			Name:    "百度",
			Path:    "https://www.baidu.com",
			AppType: "web",
			Icon:    "https://pss.bdstatic.com/static/superman/img/qrcode_download-02b84e1f66.png",
		},
		{
			Name:    "Google",
			Path:    "https://www.google.com",
			AppType: "web",
			Icon:    "https://www.google.com/favicon.ico",
		},
		{
			Name:    "GitHub",
			Path:    "https://github.com",
			AppType: "web",
			Icon:    "https://github.githubassets.com/favicons/favicon.svg",
		},
		{
			Name:    "微信开发者文档",
			Path:    "https://developers.weixin.qq.com/doc/",
			AppType: "web",
			Icon:    "https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico",
		},
	}
}